<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use fast\Tree;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use PHPExcel;
use app\admin\model\CustomsClearance as MyModel;
use app\admin\model\CustomsGoods;
use think\Model;

/**
 * 报关信息
 *sp_customs_goods
 * @icon fa fa-circle-o
 */
class CustomsClearance extends Backend
{
    
    /**
     * CustomsClearance模型对象
     * @var \app\admin\model\CustomsClearance
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\CustomsClearance;
        $this->view->assign("typeList", $this->model->getTypeList());
    }

    public function import()
    {
        //        $file = $this->request->request('file');

        //        require  EXTEND_PATH.'PHPExcel\PHPExcel.php';
        //        require  EXTEND_PATH.'PHPExcel\PHPExcel\IOFactory.php';

        $impfile = $this->request->request('file');
        //取出文件后缀名
        $temp_arr = explode(".", $impfile);
        $file_ext = array_pop($temp_arr);
        $file_ext = trim($file_ext);
        $file_ext = strtolower($file_ext);
        $extension = $file_ext;
        if($extension!='xls' && $extension!='xlsx') {
            dd('aaa');
            //            return resultArray(['error' => '请上传xls、xlsx文件格式']);
        }

        //        if( $extension =='xlsx' )
        //        {
        //            $objReader = new \PHPExcel_Reader_Excel2007();
        //        }
        //        else
        //        {
        //            $objReader = new \PHPExcel_Reader_Excel5();
        //        }

        $objExcel = new \PHPExcel();
        $filename  = $impfile;
        if($extension == 'xlsx') {
            //            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
            $objReader = new \PHPExcel_Reader_Excel2007();
            $objPHPExcel = $objReader->load($filename, $encode = 'utf-8');
        }else if($extension == 'xls'){
            //            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
            $objReader = new \PHPExcel_Reader_Excel5();
            $objPHPExcel = $objReader->load($filename, $encode = 'utf-8');
        }
        $excel_array = $objPHPExcel->getsheet(0)->toArray();   //转换为数组格式

        unset($excel_array[0]);
        if(empty($excel_array)){
            return false;
        }
        //        dd($excel_array);
        foreach ($excel_array as $k=>$v){
            $rs = array_chunk($v,12);
            //            $model->where
            $rs0 = $rs[0];
            $rs1 = $rs[1];
            $data['declareNo']=$rs0[0];//报关单号
            if($data['declareNo']){
                $info = MyModel::where($data)->find();
                if(empty($info)){
                    $data['bookNo']=$rs0[1];//账册号
                    $data['entryPort']=$rs0[2];//入境口岸
                    $data['entry_time']=strtotime($rs0[3]);//入境时间
                    $data['release_time']=strtotime($rs0[4]);//放行时间
                    $data['guarantees_time']=strtotime($rs0[5]);//担保时间
                    $data['declare_time']=strtotime($rs0[6]);//报关时间
                    $data['entryStorehouse']=$rs0[7];//仓库位置
                    $data['entryChain']=isset($rs0[8])?$rs0[8]:'';//入境联
                    $data['declareChain']=isset($rs0[9])?$rs0[9]:'';//关报联
                    $data['releaseChain']=isset($rs0[10])?$rs0[10]:'';//放行联
                    $data['type']=$rs0[11];//是否传递给浪潮
                    $data['createtime']=time();//
                    $data['is_succ']=1;//
                    $info = MyModel::create($data);
                    if(!empty($rs1)){
                        $da['customs_id'] = $info['id'];
                        $da['productName'] = $rs1[0];//商品名
                        $da['productOrigin'] = $rs1[1];//产地
                        $da['productPrice'] = $rs1[2];//价格
                        $da['productVat'] = $rs1[3];//增值税
                        $da['productTariff'] = $rs1[4];//关税
                        $da['productExcise'] = $rs1[5];//消费税
                        $da['productCate'] = $rs1[6];//品类
                        $da['count'] = $rs1[7];//数量
                        $da['grossWeight'] = $rs1[8];//毛重
                        $da['netWeight'] = $rs1[9];//净重
                        $da['is_succ'] = $rs1[10];//净重
                        CustomsGoods::create($da);
                    }

                }
            }
            //            dd($data);


            //            $this->error('失败');

            //            dd($rs);
        }
        $this->success('成功');
        //        $this->error('失败');
        //        return $excel_array;


        //        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $customsInfo=$this->model->where('declareNo','=',$params['declareNo'])->find();
                    if ($customsInfo){
                        $this->error('当前报关单号已设置');
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    if ($params['type']==2){
                        $sendInfo=$params;
                        unset($sendInfo['type']);
                        $sendInfo['entryTime']= date('Ymd',strtotime($sendInfo['entry_time']));
                        $sendInfo['releaseTime']= date('Ymd',strtotime($sendInfo['release_time']));
                        $sendInfo['guaranteesTime']=date('Ymd',strtotime($sendInfo['guarantees_time']));
                        $sendInfo['declareTime']=date('Ymd',strtotime($sendInfo['declare_time']));
                        $sendInfo['product']=[];
                        unset($sendInfo['declare_time']);
                        unset($sendInfo['guarantees_time']);
                        unset($sendInfo['release_time']);
                        unset($sendInfo['entry_time']);
                        $sendInfo['companyUscc']='123123';
                        $sendLang= json_encode($sendInfo);
                        $aes= openssl_encrypt($sendLang, 'AES-128-ECB', 'zAfR%4hrIaF8!ykY', 0);
                        $sendUrl='https://api.dm.intelliquor.com/ch-system-api/sz/saveCustomsDeclare';
                        $aa= send_request($sendUrl,$aes);
                        //if ($aa['code']==200){
                            $this->model->where('id','=',$this->model->id)->update(['is_succ'=>2]);
//                        }else{
//                            $this->model->where('id','=',$this->model->id)->update(['is_succ'=>3]);
//                        }
                    }
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    public function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }

            $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                $primaryvalue = implode(',', $primaryvalue);

                $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->model->order($order);
            }

            $datalist = $this->model->where($where)
                ->page($page, $pagesize)
                ->select();

            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                if ($this->selectpageFields == '*') {
                    $result = [
                        $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                        $field      => isset($item[$field]) ? $item[$field] : '',
                    ];
                } else {
                    $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
                }
                $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
                $list[] = $result;
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }

}
